package com.zz.zzliving.commodity.util;

import com.zz.zzliving.commodity.entity.BaseTree;
import com.zz.zzliving.commodity.entity.CategoryEntity;

import java.util.List;
import java.util.stream.Collectors;

public class HandleTree {

    /**
     * 为每一个commodity填充对应的child属性，并返回
     * @param commodity
     * @param allCommodities
     * @return childer
     */
    public static List<CategoryEntity> handleToChildrenT(CategoryEntity commodity, List<CategoryEntity> allCommodities){
        if(commodity == null){
            return null;
        }
        List<CategoryEntity> collect = allCommodities.stream().filter(child -> child.getParentId().equals(commodity.getId())).sorted((com1, com2) -> (int) (com2.getId() - com1.getId())).collect(Collectors.toList());
        commodity.setChildren(collect);
        return collect;
    }

    /**
     * 每一次最外层的集合变量，初始化每一个childer
     * @param parentList 最外层的实体类
     * @param allCommodities 全部的实体类
     * @return 最终的Tree形态
     */
    public static List<CategoryEntity> handleTToTree(List<CategoryEntity> parentList, List<CategoryEntity> allCommodities){
        if(parentList == null || allCommodities == null || parentList.size() == 0){
            return parentList;
        }
        //接下来能保证parentList中存在数据
        for (int i = 0; i < parentList.size(); i++) {
            //取出每一个外层的T，并初始化childer
            CategoryEntity commodity = parentList.get(i);
            List<CategoryEntity> childrenT = handleToChildrenT(commodity, allCommodities);
            handleTToTree(childrenT, allCommodities);
        }
        return parentList;
    }
}
